import React from "react";
import {connect} from 'react-redux'
import {List,Badge} from 'antd-mobile'

@connect(
  state=>state
)
class Msg extends React.Component{
    getLast(arr){
        //取最后一条信息
        console.log(arr)
        return arr[arr.length-1]
       
      }
      render() {
        const Item = List.Item
        const Brief = Item.Brief
        const userid = this.props.user._id
        const userinfo = this.props.chat.users
        //按照聊天用户分组，根据chatid
        const msgGroup = {}
        this.props.chat.chatmsg.forEach(v=>{
          msgGroup[v.chatid] = msgGroup[v.chatid]||[]
          msgGroup[v.chatid].push(v)
        })
        //新发的消息排在前面
        const chatList = Object.values(msgGroup).sort((a,b)=>{
          const a_last = this.getLast(a).create_time,
                b_last = this.getLast(b).create_time
          console.log(a_last)
          return b_last - a_last
        })
        console.log(chatList)
        return (
          <div>
              {chatList.map(v=>{
                const lastItem = this.getLast(v)
                const targetId = v[0].from ===userid?v[0].to:v[0].from
                if(!this.props.chat.chatmsg.length ){
                  return null
                }
                if(!userinfo[targetId]){
                  return null
                }
                // name和头像的取值
                const name = userinfo[targetId]?userinfo[targetId].name:'ghost'
                const avatar =userinfo[targetId]?userinfo[targetId].avatar:'pig'
                // v.read为false,且是发给我的id
                const unreadNum = v.filter(v=>!v.read&&v.to===userid).length
    
                return(
                  <List key={lastItem._id}>
                  <Item
                    extra={<Badge text={unreadNum}/>}
                    thumb={require(`../img/${avatar}.png`)}
                    arrow="horizontal"
                    onClick={()=>{
                      this.props.history.push(`/chat/${targetId}`)
                    }}
                    style={{zIndex:10}}
                  >
                    {name}
                    <Brief>{lastItem.content}</Brief>
                  </Item>
                  </List>
                  
                )
              })}
          </div>
        )
      }
    }
    
    export default Msg